<template>
  <d2-container>
    <el-tabs type="card" v-model='activeName'>
      <el-tab-pane label="班级详情" name='detail'>
        <el-main style='background-color: white;position: relative;'>
          <div style="margin-bottom: 20px;font-size: 20px">
            <div style="display: inline-block;color:#98A0A7">课程班级: <span style="color:black;margin-left: 10px">{{class_info.name}}</span></div>
          </div>

          <div style="margin-bottom: 20px;font-size: 20px">
            <div style="display: inline-block;color:#98A0A7">上课教室:<span style="color:black;margin-left: 10px">{{class_info.classroomText}}</span></div>
          </div>

          <div style="margin-bottom: 20px;font-size: 20px">
            <div
              style="display: inline-block;color:#98A0A7"
            >教务老师:<span style="color:black;margin-left: 10px">{{class_info.registrar == undefined ? '暂无' : class_info.registrar.name}}</span></div>
            <!-- <el-button
              @click="selectRegistrar = true"
              type="primary"
              style="margin-left: 40px"
            >选择教务老师</el-button> -->
          </div>

          <div style="margin-bottom: 20px;font-size: 20px">
            <div
              style="display: inline-block;color:#98A0A7"
            >上课老师:<span style="color:black;margin-left: 10px">{{class_info.teacher == undefined ? '暂无' : class_info.teacher.name}}</span></div>
            <!-- <el-button @click="selectTeacher =true" type="primary" style="margin-left: 40px">选择上课老师</el-button> -->
          </div style="margin-bottom: 20px;font-size: 20px">

          <div style="margin-bottom: 20px;font-size: 20px">
            <div style="display: inline-block;color:#98A0A7">开设课程:<span style="color:black;margin-left: 10px">{{class_info.course.name}} ({{class_info.course.duration}}小时)</span></div>
          </div>

          <div style="margin-bottom: 20px;font-size: 20px">
            <div style="display: inline-block;color:#98A0A7">上课学校:<span style="color:black;margin-left: 10px">{{class_info.school.name}}</span></div>
          </div>
          <div style="margin-bottom: 20px;font-size: 20px">
            <div style="display: inline-block;color:#98A0A7">上课时间:<span style="color:black;margin-left: 10px">{{class_info.classHours}}</span></div>
          </div>

          <div style="margin-bottom: 20px;font-size: 20px"> 
            <div
              style="display: inline-block;color:#98A0A7"
            >课程时间:<span style="color:black;margin-left: 10px">{{class_info.startDate}} --- {{class_info.endDate == 'Invalid Date' ? '' : class_info.endDate}}</span></div>
          </div>

         

          <div>
            <div style="display: inline-block;position: absolute;right:300px;top:10px">
              <el-button
                @click="finishClass"
                type="primary"
                style="margin-left: 40px"
                v-if="class_info.status == 0"
              >结课</el-button>
              <el-button
                @click="finishClass"
                type="warning"
                style="margin-left: 40px"
                v-if="class_info.status == 1"
              >复课</el-button>
            </div>
          </div>

          <div>
            <div style="display: inline-block;position: absolute;right:30px;top:10px">
              <el-button
                @click="handleCourseOrderDetailClick"
                type="primary"
                style="margin-left: 40px"
              >批量订购教材</el-button>
            </div>
          </div>

           <div>
            <div style="display: inline-block;position: absolute;right:170px;top:10px">
              <el-button
                @click="transferStudentToOtherClass"
                type="primary"
                style="margin-left: 40px"
              >批量转班</el-button>
            </div>
          </div>


        </el-main>

      </el-tab-pane>

      <el-tab-pane label="学生列表" name='studentlist'>
        <el-main>
          <div>
            <h3 style="display: inline-block;">班级学生列表</h3>
          </div>

          <div>

            <el-dialog title="学生列表" :visible.sync="selectStudent">
              <el-input placeholder="请输入学生姓名" v-model="searchStudentName" size="small">
                <el-button slot="append" icon="el-icon-search" @click="searchStudent"></el-button>
              </el-input>
              <el-table :data="studentList">
                <el-table-column property="name" label="学生姓名"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button @click="addStudent(scope.row)" type="text">选择</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="selectStudent = false">关闭</el-button>
              </div>
            </el-dialog>
          </div>

          <el-table :data="class_student" border style="width: 100%;">
            <el-table-column prop="student.name" label="姓名"></el-table-column>
            <el-table-column label="扣费方式">
              <template slot-scope='scope'>
                <span v-if="scope.row.type == 0">课时</span>
                <span v-if="scope.row.type == 1">小时</span>
                <span v-if="scope.row.type == 2">包月</span>
              </template>
            </el-table-column>
            <el-table-column  label="剩余数量">
              <template slot-scope='scope'>
                <span v-if="scope.row.type == 0">{{scope.row.numberOfClasses}}</span>
                <span v-if="scope.row.type == 1">{{scope.row.numberOfHours}}</span>
                <span v-if="scope.row.type == 2">详情查看</span>
              </template>
            </el-table-column>
            <el-table-column label="上课率">
              <template slot-scope='scope'>
                <span >{{scope.row.times}}/{{scope.row.times + scope.row.missTimes}}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="gender" label="性别"></el-table-column>

            <el-table-column  label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="handleStudentDetailClick(scope.row)"
                  type="text"
                  size="normal"
                  style
                >查看</el-button>
                <el-button
                  @click="handleStudentRemoveClick(scope.row)"
                  type="text"
                  size="normal"
                  style
                >停课</el-button>
                <div></div>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-tab-pane>

      <el-tab-pane label="上课记录" name='classorder'>
        <el-main>
          <div>本周应出勤人数：{{supposedNumber}}</div>
          <el-button type='primary' style='float:right;margin-bottom: 10px' @click='exportDetail'>导出记录</el-button>
          <el-table :data="class_order_list" border style="width: 100%;">
            <el-table-column prop="supposedStudentCount" label="应上课人数"></el-table-column>
            <el-table-column prop="showCount" label="上课人数"></el-table-column>
            <el-table-column prop="missCount" label="缺勤人数"></el-table-column>
            <!-- <el-table-column  prop="showPercentage" label="出勤率(%)"> -->
              
            
            </el-table-column>
            <el-table-column  prop="commission" label="提成奖金（元）"></el-table-column>
            <el-table-column prop="createdAtText" label="开课时间"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="handleClassOrderDetailClick(scope.row)"
                  type="text"
                  size="normal"
                  style
                >查看</el-button>
                <el-button
                  @click="handleCommission(scope.row)"
                  type="text"
                  size="normal"
                  style
                >修改奖金</el-button>
                <div></div>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-tab-pane>
    </el-tabs>
    <!-- <el-dialog title="选择教务老师" :visible.sync="selectRegistrar">
      <el-form>
        <el-form-item label="老师姓名">
          <el-input v-model="staffName" style="width:50%;margin-right:10px" autocomplete="off"></el-input>
          <el-button type="primary" @click="searchRegistrar">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-table :data="staffList" border>
            <el-table-column property="name" label="姓名"></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="registrarInfo(scope.row)"
                  type="text"
                  size="mini"
                  style="text-align: center"
                 @current-change="currentChange"
                >选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination small layout="prev, pager, next" :total="total"></el-pagination>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectRegistrar = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择上课老师" :visible.sync="selectTeacher">
      <el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectTeacher = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog> -->

    <el-dialog title="修改奖金" :visible.sync="showCommission">
              <el-input placeholder="修改奖金（元）" v-model="newCommission" type='number' step='0.1' >
              </el-input>
             
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="updateCommission">确定</el-button>
                <el-button type="secondary" @click="showCommission = false">关闭</el-button>
              </div>
   </el-dialog>

  </d2-container>
</template>


<script>
    import request from "@/plugin/axios";
    import formatTime from '@/libs/util.formatTime.js'
    import excel from '@/libs/util.excel.js'
    export default {
        data() {
            return {
              showCommission : false,
                class_id: undefined,
                class_student: undefined,
                class_info: {'course':{},'school':{}},
                class_order_list: undefined,
                studentList : [],
                selectStudent : undefined,
                searchStudentName : undefined,
                disabled : true,
                activeName : 'detail',
                newCommission : 0,
                commissionID : undefined,
                supposedNumber : undefined,
                cnweek : ['日','一','二','三','四','五','六']

            };
        },
        methods: {
            
          handleCommission(e){
            this.commissionID = e._id
            this.showCommission = true
          },

          updateCommission(){
            console.log(this.newCommission,'dsdss')
            this.$confirm('如果提成已经发放，请联系财务修改。','确定修改提成吗？',{}).then(()=>{
              request({
                    url: "/staffCommission/updateCommission",
                    method: "post",
                    data: {
                       id : this.commissionID,
                       commission : this.newCommission
                    }
                }).then(res => {
                    if (res.code == 200){
                      this.$message('修改成功！')
                      this.commissionID = undefined
                      this.showCommission = false
                      this.newCommission = 0
                      this.getClassOrderList()
                    }

                });
            }).catch(()=>{

            })
            
          },
          hourConvert(hour){
            let m = this.addZero(parseInt(hour * 30 % 60))
            let h = this.addZero(parseInt(Math.floor(hour /2 )))
            return String(h + ':' + m)
        },
        addZero(m){
            if (m < 10){
                return '0' + m
            }
            else{
                return String(m)
            }
        },
            getStudentList(page) {
                request({
                    url: "/student/getStudentList",
                    method: "post",
                    data: {
                        page: page,
                        pageSize: 100,
                        name: this.searchStudentName,
                        school: this.class_info.school._id
                    }
                }).then(res => {
                    this.studentList = res.data;
                    this.searchStudentCount = res.data.count;

                });
            },
            searchStudent() {
                this.getStudentList(1);
            },

            getThisWeekStudentCount(){
              
               request({
                    url: "/class/getThisWeekSupposedStudentCount",
                    method: "post",
                    data: {_id: this.class_id}
                }).then(res => {
                  if (res.code == 200){
                    this.supposedNumber = res.data
                  }
                })
            },
            getClassStudentList() {
                request({
                    url: "/class/getClassStudentList",
                    method: "post",
                    data: {_id: this.class_id}
                }).then(res => {
                    if (res.code == 200) {
                      
                        this.class_student = res.data
                        this.class_student.forEach((value, index) => {
                          console.log(value.gender,'sds00')
                            this.class_student[index].gender = value.student.gender === 0 ? '男' : '女'
                        })
                    }

                });
            },


            getClassDetail() {
                request({
                    url: "/class/getClassOne",
                    method: "post",
                    data: {_id: this.class_id}
                }).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        if(res.data.classroom == null){
                            res.data.classroomText = '暂无'
                        }else{
                            res.data.classroomText = res.data.classroom.name
                        }
                        res.data.course = res.data.course == undefined ? {'name':''} : res.data.course
                        let temp = ''
                        res.data.hours.forEach((hourx,index2)=>{
                            if (temp.length != 0){
                                temp += ' '
                            }
                            for (var i = 0 ; i < hourx.hours.length ;i++){
                                temp += '周' + this.cnweek[index2] + ':' + this.hourConvert(hourx.hours[i].start) + ' - ' + this.hourConvert(hourx.hours[i].end)
                            }
                        })
                        res.data.classHours = temp
                        this.class_info = res.data
                    }

                });
            },


            getClassOrderList() {
                request({
                    url: "/classOrder/getClassOrderList",
                    method: "post",
                    data: {class: this.class_id}
                }).then(res => {
                    if (res.code == 200) {
                                              this.class_order_list = res.data == undefined ? [] : res.data

                        for (var i = 0 ; i < this.class_order_list.length ; i++){
                          // this.class_order_list[i].supposedStudentCount = this.class_order_list[i].supposedStudentCount || 0
                          this.class_order_list[i].createdAtText = formatTime.formatTime(this.class_order_list[i].createdAt)
                          // this.class_order_list[i].attendence = this.class_order_list[i].showPercentage
                        }
                    }

                });
            },

            finishClass(){
              this.$confirm('','确定要' + (this.class_info.status == 1 ? '复课' : '结课') +  '吗？',{}).then(res=>{
                request({
                    url: "/class/finishClass",
                    method: "post",
                    data: {class: this.class_id,status: this.class_info.status == 1 ? 0 : 1}
                }).then(res => {
                    if (res.code == 200) {
                        this.$message(this.class_info.status == 0 ? '结课成功' : '复课成功')
                    }
                    this.class_info.status = this.class_info.status == 0 ? 1 : 0

                });
              }).catch(res=>{})
            },

            handleClassOrderDetailClick(e) {
                this.$router.push({path: '/class-order-detail?id=' + e._id})
            },

            handleCourseOrderDetailClick() {
                this.$router.push({path: '/batch-product?id=' + this.class_id})
            },


            handleStudentDetailClick(e) {
                this.$router.push({path: '/student-detail?id=' + e.student._id})
            },

            transferStudentToOtherClass() {
                this.$router.push({path: '/transfer-student?id=' + this.class_id})
            },


            addStudent(e){
                // modal 
                this.$confirm("此操作将添加该学生到本班级, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                  })
                    .then(() => {
                      request({
                        url: "/class/addStudentToClass",
                        method: "post",
                        data: { id: e._id,classID : this.class_info._id }
                      }).then(res => {
                        if (res.code == 200) {
                          this.$message({
                            message: "添加成功"
                          });
                          this.getClassStudentList();
                        }
                      });
                    })
                    .catch(() => {
                      this.$message({
                        type: "info",
                        message: "已取消操作"
                      });
                    });

            },
        handleStudentRemoveClick(e){
                // modal 
                this.$confirm("此操作将该学生从本班级停课, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                  })
                    .then(() => {
                      request({
                        url: "/class/removeStudentFromClass",
                        method: "post",
                        data: { id: e.student._id,classID : this.class_info._id }
                      }).then(res => {
                        if (res.code == 200) {
                          this.$message({
                            message: "停课成功"
                          });
                          this.getClassStudentList();
                        }
                      });
                    })
                    .catch(() => {
                      this.$message({
                        type: "info",
                        message: "已取消操作"
                      });
                    });

            },

            exportDetail(){
              request({
                        url: "/classOrder/exportClassOrderExcel",
                        method: "post",
                        data: { class : this.class_info._id }
                      }).then(res => {
                        if (res.code == 200) {
                          let firstRow = '班级:' + res.data.class.name + '   授课老师：' + (res.data.class.teacher == null ? '未知' : res.data.class.teacher.name)
                          + '   教务老师：' + (res.data.class.registrar == null ? '未知' : res.data.class.registrar.name) + '       1代表出席，0代表缺席，x代表无记录'
                          console.log(firstRow,res.data.columns,res.data.data)
                          let colWidth = [{wch:10}]
                          for (var i = 1 ; i < res.data.columns.length ; i++){
                            colWidth.push({wch:3})
                          }
                          excel.export(res.data.columns,res.data.data,res.data.class.name + '上课记录',firstRow,colWidth)
                        }
                      })
            },
            load(){
              if (this.$route.query.class_id != undefined) {
                this.class_id = this.$route.query.class_id;
                this.getClassStudentList();
                this.getClassDetail();
                this.getClassOrderList();
                this.getThisWeekStudentCount()
              }
              if (this.$route.query.tab != undefined){
                  this.activeName = this.$route.query.tab
              }
            }
        },
        
    // searchRegistrar() {
    //   this.getDataList();
    // },

    // getDataList() {
    //   let data = {};
    //   data.page = this.currentPage;
    //   data.pageSize = 10;
    //   if (this.staffName) {
    //     data.name = this.staffName;
    //   }
    //   request({
    //     url: "/staff/getStaffList",
    //     method: "post",
    //     data: data
    //   }).then(res => {
    //     console.log(res);
    //     this.staffList = res.data.staff;
    //     this.total = res.data.total;
    //     this.currentPage = res.data.currentPage;
    //   });
    // },
    // currentChange(e){
    //     this.currentPage = e;
    //     this.getDataList();
    // },
    // registrarInfo(e){
    //     this.$confirm('确认'+ e.name + '选为教务老师', '请确认操作', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'info '
    //     }).then(() => {
    //       this.$message({
    //         type: 'success',
    //         message: '删除成功!'
    //       });
    //     }).catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消删除'
    //       });          
    //     });
    //     console.log(e)
    // }

        beforeRouteEnter(to,from,next){
            console.log(to.meta.refresh == 'a','tee',to.meta.refresh)
            if (to.meta.refresh == 'a'){
                to.meta.refresh = undefined
                next(v=>{
                v.load()
                })
            }
            else{
                next()
            }

        },


        created() {
            this.load()
        }
};
</script>
